from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet

from meiduo_admin.serializers.orders import OrderInfoSerialzier
from meiduo_admin.utils import PageNum
from orders.models import OrderInfo

class OrderView(ReadOnlyModelViewSet):
    # 指定查询集
    queryset = OrderInfo.objects.all()
    # 指定序列化器
    serializer_class = OrderInfoSerialzier
    # 指定权限
    permission_classes = [IsAdminUser]
    # 指定分页器
    pagination_class = PageNum


    def get_queryset(self):
        # 默认返回
        # return self.queryset
        # 对前端传递keyword判断返回不同的查询集数据
        # 1、获取keyword数据
        keyword = self.request.query_params.get('keyword')
        # 2、判断keyword
        if keyword is None or keyword == '':
            return OrderInfo.objects.filter()
        else:
            return OrderInfo.objects.filter(order_id__contains=keyword)


    # 修改订单状态
    @action(methods=['put'],detail=True)
    def status(self,request,pk):
        # 1、根据id查询订单
        try:
            order=OrderInfo.objects.get(order_id=pk)
        except:
            return Response({'error':'错误的订单编号'},status=400)
        # 2、修改订单状态
        order.status=request.data.get('status')
        order.save()
        # 3、返回结果
        return Response({'message':'ok'},status=201)